<template>
  <div>
    <!-- 筛选区域 -->
    <div class="filter-section">
      <!-- <h3>筛选条件</h3> -->
      <div class="filter-row">
        <div class="filter-item">
          <!-- <span>显示状态：</span> -->
          <el-select
            v-model="filterData.displayStatus"
            placeholder="请选择显示状态"
            clearable
          >
            <el-option
              v-for="status in options.displayStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <!-- <span>系统标签：</span> -->
          <el-select
            v-model="filterData.systemTag"
            placeholder="请选择系统标签"
            clearable
          >
            <el-option
              v-for="tag in options.systemTags"
              :key="tag.value"
              :label="tag.label"
              :value="tag.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <!-- <span>系统名称：</span> -->
          <el-input
            v-model="filterData.systemName"
            placeholder="请输入系统名称"
            clearable
          />
        </div>
        <div class="filter-item">
          <!-- <span>系统编码：</span> -->
          <el-input
            v-model="filterData.systemCode"
            placeholder="请输入系统编码"
            clearable
          />
        </div>
        <div class="filter-item">
          <el-button type="primary" @click="loadData">搜索</el-button>
          <el-button @click="handleResetFilter">重置</el-button>
        </div>
      </div>
    </div>
    <div class="system-management">
      <!-- 操作按钮和排序 -->
      <div class="operation-section">
        <div class="left-actions">
          <el-button type="primary" @click="handleAdd"  v-permission="'admin:user/system_management:add'">
            <el-icon><Plus /></el-icon>
            添加系统
          </el-button>
        </div>
        <div class="right-sort">
          <el-button-group>
            <el-button 
              :type="sortType === 'sort' ? 'primary' : ''" 
              @click="toggleSort('sort')"
            >
              {{ getSortButtonText('sort') }}
            </el-button>
            <el-button 
              :type="sortType === 'create_time' ? 'primary' : ''" 
              @click="toggleSort('create_time')"
            >
              {{ getSortButtonText('create_time') }}
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table
          :data="tableData"
          v-loading="loading"
          border
          style="width: 100%"
        >
          <el-table-column prop="system_code" label="系统编码" width="120" />
          <el-table-column prop="system_name" label="系统名称" width="120" />
          <el-table-column prop="system_tag" label="系统标签" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.system_tag === 'front' ? 'primary' : 'success'">
                {{ scope.row.system_tag === 'front' ? '前台模块' : '后台模块' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column prop="icon" label="图标" width="80">
            <template #default="scope">
              <div v-if="scope.row.icon" class="icon-preview">
                <img :src="scope.row.icon" alt="图标" />
              </div>
              <div v-else class="default-icon">
                <span>默认</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="is_external" label="是否外链" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.is_external === 'yes' ? 'danger' : 'info'">
                {{ scope.row.is_external === 'yes' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="display_status" label="显示状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.display_status === 'show' ? 'success' : 'info'">
                {{ scope.row.display_status === 'show' ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          <el-table-column prop="create_time" label="创建时间" width="160" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" @click="handleEdit(scope.row)" v-permission="'admin:user/system_management:edit'">
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row.id!)" v-permission="'admin:user/system_management:del'"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 表单弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="formData.id ? '编辑系统' : '添加系统'"
        width="70%"
        :close-on-click-modal="false"
      >
        <SystemForm
          ref="systemFormRef"
          :form-data="formData"
        />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleFormSubmit">
              {{ formData.id ? '修改' : '添加' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import SystemForm from '@/components/SystemForm.vue';
import { systemApi } from '@/api/system';
import type { SystemItem, SystemFilter, SystemForm as SystemFormType } from '@/types/system';
import { convertKeysToSnakeCase } from '@/utils/caseConverter'

// 响应式数据
const loading = ref(false);
const tableData = ref<SystemItem[]>([]);
const dialogVisible = ref(false);
const systemFormRef = ref(); // 表单引用
const sortType = ref<'sort' | 'create_time'>('sort');
const sortDirection = ref<'asc' | 'desc'>('asc');




// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const formData = reactive<SystemFormType>({
  systemCode: '',
  systemName: '',
  systemTag: '',
  sort: '',
  icon: '',
  isExternal: '',
  displayStatus: '',
  remark: ''
});

// 筛选数据
const filterData = reactive<SystemFilter>({
  displayStatus: '',
  systemTag: '',
  systemName: '',
  systemCode: ''
});

// 选项数据
const options = {
  systemTags: [
    { label: '前台模块', value: 'front' },
    { label: '后台模块', value: 'back' }
  ],
  yesNoOptions: [
    { label: '是', value: 'yes' },
    { label: '否', value: 'no' }
  ],
  displayStatusOptions: [
    { label: '显示', value: 'show' },
    { label: '隐藏', value: 'hide' }
  ]
};

// 生命周期
onMounted(() => {
  loadData();
});

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    const result = await systemApi.getSystemList(
      filterData,
      pagination.currentPage,
      pagination.pageSize,
      sortType.value,
      sortDirection.value
    );
    
    tableData.value = result.list;
    pagination.total = result.total;
  } catch (error: any) {
    ElMessage.error(error.message || '加载数据失败');
  } finally {
    loading.value = false;
  }
};

const handleAdd = () => {
  handleFormReset();
  dialogVisible.value = true;
};

const handleEdit = async (row: SystemItem) => {
  try {
    // 获取最新数据
    const detail = await systemApi.getSystemDetail(row.id!);
    Object.assign(formData, {
      id: detail.id,
      systemCode: detail.system_code,
      systemName: detail.system_name,
      systemTag: detail.system_tag,
      sort: detail.sort.toString(),
      icon: detail.icon || '',
      isExternal: detail.is_external,
      displayStatus: detail.display_status,
      remark: detail.remark || ''
    });
    
    dialogVisible.value = true;
  } catch (error: any) {
    ElMessage.error(error.message || '获取详情失败');
  }
};

// 在 SystemForm 组件中暴露方法，这里直接调用
const handleFormSubmit = async () => {
  if (!systemFormRef.value) return;
  
  try {
    // 手动触发表单验证
    await systemFormRef.value.handleSubmit();
    
    // 如果验证通过，继续处理数据
    const systemData = {
      systemCode: formData.systemCode,
      systemName: formData.systemName,
      systemTag: formData.systemTag as 'front' | 'back',
      sort: parseInt(formData.sort),
      icon: formData.icon,
      isExternal: formData.isExternal as 'yes' | 'no',
      displayStatus: formData.displayStatus as 'show' | 'hide',
      remark: formData.remark
    };

    if (formData.id) {
      // 编辑
      let json = convertKeysToSnakeCase(systemData)
      await systemApi.updateSystem(formData.id,json)
      ElMessage.success('修改成功');
    } else {
      // 新增
      let json = convertKeysToSnakeCase(systemData)
      await systemApi.createSystem(json)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false;
    handleFormReset();
    loadData();
  } catch (error: any) {
    // 错误信息已经在子组件中显示
    console.error('表单提交错误:', error);
    if(error.code == 500||error.code == 400){
      ElMessage.error(error.message)
    }
  }
};

const handleFormReset = () => {
  Object.assign(formData, {
    id: undefined,
    systemCode: '',
    systemName: '',
    systemTag: '',
    sort: '',
    icon: '',
    isExternal: '',
    displayStatus: '',
    remark: ''
  });
};

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除这条记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await systemApi.deleteSystem(id);
    ElMessage.success('删除成功');
    loadData();
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败');
    }
  }
};

const handleResetFilter = () => {
  Object.assign(filterData, {
    displayStatus: '',
    systemTag: '',
    systemName: '',
    systemCode: ''
  });
  loadData();
};

const toggleSort = (type: 'sort' | 'create_time') => {
  if (sortType.value === type) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
  } else {
    sortType.value = type;
    sortDirection.value = 'asc';
  }
  loadData();
};

const getSortButtonText = (type: 'sort' | 'create_time') => {
  if (sortType.value !== type) return type === 'sort' ? '排序' : '创建时间';
  return (type === 'sort' ? '排序' : '创建时间') + 
    (sortDirection.value === 'asc' ? ' ↑' : ' ↓');
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadData();
};
</script>

<style scoped>
.system-management {
  padding: 20px;
  margin: 0 auto;
}

.filter-section {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 2px;
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
}

.operation-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0px;
}

.table-section {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  padding: 15px;
  display: flex;
  justify-content: flex-end;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.filter-item {
  flex: 1;
  min-width: 200px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.icon-preview {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.icon-preview img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.default-icon {
  width: 40px;
  height: 40px;
  background: #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}
</style>